package com.ambitor.ipro.app.sche;

import java.util.Date;
import java.util.List;

import com.ambitor.grass.sql.dao.SuperDao;
import com.ambitor.grass.util.data.DataMap;
import com.ambitor.grass.util.data.DatasetList;
import com.ambitor.grass.util.data.IData;
import com.ambitor.grass.util.data.IDataset;
import com.ambitor.ipro.entities.UninstallSetting;
import com.ambitor.ipro.exceptions.ProException;
import com.ambitor.ipro.service.TopService;
import com.ambitor.ipro.util.Constants;
import com.ambitor.ipro.util.ResultCode;
import com.ambitor.ipro.util.SkyenccUtil;
import com.taobao.api.domain.Item;

public class Uninstaller extends BaseExecutor {

	public Uninstaller(SuperDao superDao, TopService topService) {
		super(superDao, topService);
	}

	@SuppressWarnings("unchecked")
	public void uninstall() {
		logTaskStart();
		try {
			IData userSession = getUserSession();
			int[] result = _uninstall(userSession);
			logTaskEnd(result);
		} catch (ProException e) {
			logTaskQuit(e);
		}
	}

	@SuppressWarnings("unchecked")
	private int[] _uninstall(IData userSession) throws ProException {
		String nick = userSession.getString("NICK");
		String sessionId = userSession.getString("SESSION_ID");
		String place = task.getString("PLACE");
		IDataset iidListToBeUnins = getItemsToUninstall(userSession);
		if (iidListToBeUnins == null || iidListToBeUnins.size() == 0) {
			throw new ProException(ResultCode.BUSSINESS_EXCEPTION,
					"获取待卸载的宝贝为空，请尝试其它卸载方式");
		}
		int errorNum = 0;
		for (int index = 0; index < iidListToBeUnins.size(); index++) {
			IData iidRow = null;
			try {
				iidRow = iidListToBeUnins.getData(index);
			} catch (Exception e) {
				throw new ProException(ResultCode.EXCEPTION,
						"iidListToBeUnins.getData异常", e);
			}
			String iid = iidRow.getString("INSTALL_IID", iidRow
					.getString("IID"));
			IData tradePro = new DataMap();
			tradePro.put("BATCH_ID", task.getString("BATCH_ID"));
			tradePro.put("IID", iid);
			tradePro.put("PLACE", task.getString("PLACE"));
			tradePro.put("LOG_TIME", SkyenccUtil.formatDate(new Date()));
			try {
				Long numIid = Long.valueOf(iid);
				//String oldDesc = 
				topService.uninstallPromotionModule(sessionId,
						nick, numIid, place);
				tradePro.put("TRADE_STATE", Constants.FLAG_YES);// 成功
				//tradePro.put("ITEM_DESC", oldDesc);
				deleteItemPro(tradePro);
			} catch (ProException e) {
				errorNum++;
				tradePro.put("TRADE_STATE", Constants.FLAG_NO);// 失败
				tradePro.put("EXP_TYPE", e.getType());
				tradePro.put("EXP_DESC", e.getDesc());
				tradePro.put("EXP_CODE", e.getCode());
				tradePro.put("EXP_MSG", e.getMsg());
				tradePro.put("EXP_SUB_CODE", e.getSubCode());
				tradePro.put("EXP_SUB_MSG", e.getSubMsg());
				continue;
			} finally {
				try {
					IData param = new DataMap();
					param.put("BATCH_ID", task.getString("BATCH_ID"));
					param.put("IID", iid);
					superDao.delete("TL_P_TRADE_PRO", param, new String[] {
							"BATCH_ID", "IID" });
					superDao.insert("TL_P_TRADE_PRO", tradePro);
				} catch (Exception exp) {
					logger.error("新增tradePro日志出现数据库异常", exp);
				}
			}
		}
		return new int[] { iidListToBeUnins.size(), errorNum };
	}

	@SuppressWarnings("unchecked")
	private IDataset getItemsToUninstall(IData userSession) throws ProException {
		if (retryFlag) {
			IData param = new DataMap();
			param.put("BATCH_ID", task.getString("BATCH_ID"));
			param.put("TRADE_STATE", Constants.FLAG_NO);
			try {
				return superDao.queryList("TL_P_TRADE_PRO", param);
			} catch (Exception e) {
				throw new ProException(ResultCode.DB_EXCEPTION, "获取pro_id="
						+ task.getString("BATCH_ID") + "安装失败宝贝出现异常", e);
			}
		}

		IDataset itemListToBeUnins = new DatasetList();
		if (UninstallSetting.BATCH_UNINSTALL.equalsIgnoreCase(task
				.getString("UNINSTALL_SETTING"))) {
			IData param = new DataMap();
			param.put("PRO_ID", task.getString("PRO_ID"));
			try {
				itemListToBeUnins = superDao.queryList("TF_P_ITEM_PRO", param);
			} catch (Exception e) {
				throw new ProException(ResultCode.DB_EXCEPTION,
						"获取TF_P_ITEM_PRO发生数据库异常", e);
			}
		} else if (UninstallSetting.USER_UNINSTALL.equalsIgnoreCase(task
				.getString("UNINSTALL_SETTING"))) {
			IData param = new DataMap();
			param.put("USER_ID", task.getString("USER_ID"));
			try {
				itemListToBeUnins = superDao.queryList("TF_P_ITEM_PRO", param);
			} catch (Exception e) {
				throw new ProException(ResultCode.DB_EXCEPTION,
						"获取TF_P_ITEM_PRO发生数据库异常", e);
			}
		}else if (UninstallSetting.ALL_UNINSTALL.equalsIgnoreCase(task
				.getString("UNINSTALL_SETTING"))) {
			String sessionId = userSession.getString("SESSION_ID");
			String nick = userSession.getString("NICK");
			List<Item> itemList = topService.getAllItems(sessionId, nick);
			for (Item item : itemList) {
				IData data = new DataMap();
				data.put("IID", item.getNumIid().toString());
				itemListToBeUnins.add(data);
			}
		}
		return itemListToBeUnins;
	}
}
